package net.zzy.pbbot.plugin.anime.service;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import net.lz1998.pbbot.utils.Msg;
import net.zzy.pbbot.plugin.anime.entity.AnimeData;
import net.zzy.pbbot.plugin.anime.entity.AnimeResp;
import net.zzy.pbbot.util.HttpsUtils;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

import static net.zzy.pbbot.finalfield.Api.ANIME_URL;
import static net.zzy.pbbot.finalfield.FinalInt.ANIME_MAX_NUM;
import static net.zzy.pbbot.finalfield.FinalStr.ANIME_RESP_OK;

/**
 * @author zhuZhaoYang
 * @date 2021/9/24 15:05
 */
@Slf4j
@Component
public class AnimeService {
    public static Msg getAnime(String[] messages) throws Exception {
        log.info("开始获取番剧");
        if (messages.length < 2) {
            return Msg.builder().text("请以\"番剧 数量\"的形式发送");
        }
        String resp = HttpsUtils.get(ANIME_URL + messages[1], null, null);
        AnimeResp animeResp = JSON.parseObject(resp, AnimeResp.class);
        if (!animeResp.getCode().equals(ANIME_RESP_OK)) {
            log.info("获取番剧列表失败！");
            return Msg.builder().text("获取番剧列表失败！");
        }
        if (animeResp.data.size() > ANIME_MAX_NUM) {
            return Msg.builder().text("数量请不要大于50");
        }
        // 创建400*300图片
        BufferedImage bufferedImage = new BufferedImage(600, 30 * (animeResp.data.size() + 1), BufferedImage.TYPE_INT_RGB);
        // 获取画笔
        Graphics2D g = bufferedImage.createGraphics();
        // 背景填充白色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight());
        //
        g.setFont(new Font("宋体", Font.PLAIN, 15));
        g.setColor(Color.BLACK);
        int index = 1;
        for (AnimeData data : animeResp.data) {
            String line = index + ". " + data.getName() + " 更新至" + data.getCount() + "集 更新时间：" + data.getTime();
            g.drawString(line, 10, 30 * index);
            index++;
        }
        String path = System.getProperty("user.dir") + File.separator + "image" + File.separator + "anime_temp.png";
        ImageIO.write(bufferedImage, "png", new File(path));
        return Msg.builder().image(path);
    }
}
